import os
import sys
import numpy as np
from PIL import Image

results = []
imgs = []

# workPath = '../../'
# groundTruthPath = '../../output/Images/'
workPath = './'
groundTruthPath = './mask_all/'

with open(workPath+'images/imageList.txt', 'r') as imgList:
	for image in imgList:
		img = image.rstrip()
		imgName = os.path.splitext(img)[0]
		
		# groundTruthSegName = groundTruthPath+imgName+'_resegmentation.bmp'
		groundTruthSegName = groundTruthPath+imgName+'_labels.png'
		resultSegName = workPath+'results/'+imgName+'/final_sampledSegmentation.png'

		try:
			groundTruthSeg = Image.open(groundTruthSegName)
			resultSeg = Image.open(resultSegName)
		except IOError:
			print "Invalid image:", imgName
			continue

		groundTruthSeg = np.array(groundTruthSeg)
		resultSeg = np.array(resultSeg)[:, :, :3]

		size = groundTruthSeg.size/3
		diff = abs(groundTruthSeg - resultSeg)
		diff = diff[:, :, 0] + diff[:, :, 1] + diff[:, :, 2]
		difference = np.sum(diff==0)

		imgs.append(imgName)
		results.append(float(difference)/size)
			
idx = np.argsort(results)

resultFile = open(workPath+'results/result.txt', 'w')
trundix = idx[::-1]#[:-5]
trunresults = [results[i] for i in trundix]
for i in trundix:
	resultFile.write('{}: {}\n'.format(imgs[i], results[i]))
resultFile.write('\nAverage accuracy: {}'.format(np.sum(trunresults)/len(trunresults)))